import random
import time

from utils.database._redis import RedisClients
from config import settings


class ProxyPool:
    proxy_list = []
    timer = 0

    @RedisClients.lock(settings.proxy_lock_key)
    def get_all_proxy(self) -> list:
        expired = time.time() - ProxyPool.timer

        if len(ProxyPool.proxy_list) > 0 and expired < 60:
            return ProxyPool.proxy_list
        else:
            ProxyPool.proxy_list.clear()

        for i in settings.proxy.redis_proxy_pool:
            ProxyPool.proxy_list.extend(self.get_proxy(i['key'], i['username'], i['password']))

        ProxyPool.timer = time.time()
        return ProxyPool.proxy_list

    def get_proxy(self, redis_key, username, password):
        results = RedisClients.sync_cli.zrange(redis_key, 0, -1)
        return [f"http://{username}:{password}@{_}" for _ in results]

    @classmethod
    def get_one(cls):
        self = cls()
        expired = time.time() - ProxyPool.timer

        if len(ProxyPool.proxy_list) == 0 or expired >= 60:
            self.get_all_proxy()

        return random.choice(ProxyPool.proxy_list)


if __name__ == '__main__':
    x = ProxyPool.get_one()
    print(x)
